package com.shishuo.cdn.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dotnet.common.constant.SystemConstants;
import com.dotnet.common.utils.DateUtils;
import com.dotnet.common.utils.PropertiesUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.shishuo.cdn.dao.UserDao;
import com.shishuo.cdn.entity.LoginLog;
import com.shishuo.cdn.entity.User;
import com.shishuo.cdn.entity.vo.JsonVo;
import com.shishuo.cdn.service.UserService;
import com.shishuo.cdn.util.ClientIPUtils;
import com.shishuo.cdn.util.HttpRequestUtil;
import com.shishuo.cdn.util.RegexUtils;
import com.shishuo.cdn.util.SimpleMailSender;
import com.shishuo.cdn.util.StringUtil;
import com.shishuo.cdn.util.sendsms;
import com.shishuo.cms.util.AuthUtils;

/**
 * 用户管理--登录、注册、找回密码
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/user")
public class UserAction extends BaseAction {

	/**
	 * Kaptcha 验证码
	 */
	@Autowired
	private DefaultKaptcha captchaProducer;

	@Autowired
	private UserService userService;

	@Autowired
	private UserDao userDao;

	@RequestMapping(value = "/login.htm", method = RequestMethod.GET)
	public String login(HttpServletRequest request, ModelMap modelMap) {
		return "/template/blog/index";
	}

	/**  验证用户信息 added by liaoliyun ***/

	@ResponseBody
	@RequestMapping(value = "/verify_userinfo.json", method = RequestMethod.POST)
	public JsonVo<String> verify_userinfo(@RequestParam(value = "zhifumima") String zfmm, HttpServletRequest request, ModelMap modelMap) {
		User user = (User) request.getSession().getAttribute("user");
		String userId = user.getUser_id().toString();
		// 获取用户基本信息和银行卡信息、用户手动添加的属性信息
		User userinfo = userService.getUserBankById(userId);
		JsonVo<String> json = new JsonVo<String>();
		if (null == userinfo.getBank_card()) {
			json.setResult(false);
		} else if (userinfo.getBank_card().equals("")) {
			json.setResult(false);
		} else {
			json.setResult(true);
		}
		return json;
	}

	/**  验证支付密码 added by liaoliyun ***/

	@ResponseBody
	@RequestMapping(value = "/verify_zfmm.json", method = RequestMethod.POST)
	public JsonVo<String> verify_zfmm(@RequestParam(value = "zhifumima") String zfmm, HttpServletRequest request, ModelMap modelMap) {
		refreshSessionUser(request);
		JsonVo<String> json = new JsonVo<String>();
		User user = (User) request.getSession().getAttribute("user");
		if (zfmm.equals(user.getZhifumima())) {
			json.setResult(true);
		} else {
			json.setResult(false);
			json.getErrors().put("error", "支付密码错误！");

		}
		return json;
	}

	/**
	 * 
	 * 描述：判断用户是否设置过支付密码
	 * 创建人： 魏泽超
	 * 创建时间: 2016-4-13 下午4:57:34
	 * @version
	 */
	@ResponseBody
	@RequestMapping(value = "/isSetPayPwd.json", method = RequestMethod.POST)
	public JsonVo<String> isSetPayPwd(HttpServletRequest request, ModelMap modelMap) {
		JsonVo<String> json = new JsonVo<String>();
		refreshSessionUser(request);
		User user = (User) request.getSession().getAttribute("user");
		if (null == user.getZhifumima() || ("").equals(user.getZhifumima())) {
			json.setResult(false);
		} else {
			json.setResult(true);
		}
		return json;
	}

	/** 找回登录密码 added by liaoliyun ***/
	@RequestMapping(value = "/forgetpwd.htm", method = RequestMethod.GET)
	public String forgetpwd(HttpServletRequest request, ModelMap modelMap) {
		return "/template/blog/findpwd";
	}

	@ResponseBody
	@RequestMapping(value = "/send_yzm.json", method = RequestMethod.POST)
	public JsonVo<String> sendyzm(@RequestParam(value = "account") String name, HttpServletRequest request, ModelMap modelMap) {
		// 重置验证码次数
		phoneYzmReset(request, name);
		JsonVo<String> json = new JsonVo<String>();
		User user = userService.getUserById(name);
		if (null == user) {
			json.getErrors().put("username", "用户不存在");
			json.setResult(false);
		} else {
			if (null == user.getPhoneYzmCount()) {
				user.setPhoneYzmCount(0);
			}
			// 生成验证码
			String capText = captchaProducer.createText();
			request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
			String message = "你的注册验证码为【" + capText + "】。请不要把验证码泄露给其他人。";
			String title = "运通注册验证码";
			boolean flag = false;
			if (RegexUtils.isMobileNO(name)) {
				if (user.getPhoneYzmCount() < 10) {
					String code = sendsms.sendSmsByBackPwd(name, capText);
					if ("2".equals(code)) {
						flag = true;
						phoneYzm(user.getUser_id().toString(), request, name);
					} else {
						flag = false;
					}
					if (flag) { // 存储验证码到数据库
						userService.updateYzmById(capText, user.getUser_id().toString());
					}
				} else {
					phoneYzm(user.getUser_id().toString(), request, name);
				}
			} else {
				flag = SimpleMailSender.sendSmtpMail(name, title, message);
			}

			if (!flag) {
				json.getErrors().put("code", "同一手机号码，一天只能发送10条验证码");
			}
			json.setResult(flag);

		}
		return json;
	}

	@ResponseBody
	@RequestMapping(value = "/resetmm.json", method = RequestMethod.POST)
	public JsonVo<String> resetMm(@RequestParam(value = "useId") String userId, @RequestParam(value = "Yzm") String yzm, @RequestParam(value = "newmm") String newpass, @RequestParam(value = "qrnewmm") String qrnewpass, HttpServletRequest request, ModelMap modelMap) {
		Map<String, Object> result = new HashMap<String, Object>();
		// 重置验证码次数
		phoneYzmReset(request, userId);
		JsonVo<String> json = new JsonVo<String>();
		User user = userService.getUserById(userId);
		if (null != user) {
			if (null == user.getPhoneYzmCount()) {
				user.setPhoneYzmCount(0);
			}
			String yz_mm = user.getYanzhengma();
			if (!newpass.equals(qrnewpass)) {
				json.getErrors().put("pwderror", "两次密码不一致");
				json.setResult(false);
				return json;
			}
			if ((yz_mm == null) || (yzm == "")) {
				json.getErrors().put("yzm", "验证码为空或错误");
				json.setResult(false);
				return json;

			}
			if (!yz_mm.equals(yzm)) {
				json.getErrors().put("yzm", "验证码错误");
				json.setResult(false);
				return json;
			}

			boolean flag = userService.updateUserById(AuthUtils.MD5(newpass), user.getUser_id().toString());
			String code = "";
			if (flag) {
				boolean f = false;
				if (user.getPhoneYzmCount() < 10) {
					code = sendsms.sendSmstoNewPwd(userId, newpass);
					if ("2".equals(code)) {
						f = true;
						phoneYzm(user.getUser_id().toString(), request, userId);
					}
				} else {
					phoneYzm(user.getUser_id().toString(), request, userId);
				}

				if (f) {
					result.put("status", 1);
					result.put("info", "密码已发送到您的手机上，请查收");
				} else {
					result.put("status", 0);
					if ("2".equals(code)) {
						result.put("info", "发送失败，请稍后再试...");
					} else {
						result.put("info", "同一手机号码，一天只能发送10条验证码");
					}
				}
				json.setResult(true);
			}
		}
		return json;
	}

	/***发送邮件以找回登录密码****/
	@ResponseBody
	@RequestMapping(value = "/sendmailtofindmm.json", method = RequestMethod.POST)
	public JsonVo<String> sendmailtofindmm(@RequestParam(value = "account") String account, @RequestParam(value = "mailaddr") String mailaddr, HttpServletRequest request, ModelMap modelMap) {
		JsonVo<String> json = new JsonVo<String>();
		boolean flag = false;
		User user = userService.getUserById(account);
		if (null == user) {
			json.getErrors().put("username", "用户不存在");
			json.setResult(false);
			return json;
		}
		if (null == user.getLx_mall()) {
			json.getErrors().put("mailerror", "没有注册邮箱，请用手机号找回密码");
			json.setResult(false);
			return json;
		}
		if (!user.getLx_mall().equals(mailaddr)) {
			json.getErrors().put("mailerror", "请输入注册邮箱地址");
			json.setResult(false);
			return json;
		}
		String secretKey = UUID.randomUUID().toString(); // 密钥
		String href = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/user/resetmima.htm?sid=" + secretKey + "&account=" + account;
		String title = "找回密码验证邮件，请勿回复";
		String content = "请点击【<font color=red>重置密码</font>】重置登录密码：\n\r <br><a href='" + href + "'>重置密码</a>";
		flag = SimpleMailSender.sendSmtpMail(mailaddr, title, content);
		if (flag) {
			flag = userService.updateMailYzmById(secretKey, user.getUser_id().toString());

		}
		json.setResult(flag);

		return json;
	}

	/** 邮件找回登录密码 added by liaoliyun ***/
	@RequestMapping(value = "/resetmima.htm", method = RequestMethod.GET)
	public String forgetpwdbymail(HttpServletRequest request, ModelMap modelMap, @RequestParam(value = "sid") String mailyzm, @RequestParam(value = "account") String account) {
		User user = userService.getUserById(account);
		if (user == null) {

			return null;
		}
		if (!mailyzm.equals(user.getMailyanzhengma())) {

			return null;

		}

		return "/template/blog/findpwd";
	}

	@ResponseBody
	@RequestMapping(value = "/resetmmwithmail.json", method = RequestMethod.POST)
	public JsonVo<String> resetmmwithmail(@RequestParam(value = "useId") String userId, @RequestParam(value = "newmm") String newpass, @RequestParam(value = "qrnewmm") String qrnewpass, @RequestParam(value = "mail_yzm") String mailyzm, HttpServletRequest request, ModelMap modelMap) {
		JsonVo<String> json = new JsonVo<String>();
		if (!newpass.equals(qrnewpass)) {
			json.getErrors().put("pwderror", "两次密码不一致");
			json.setResult(false);
			return json;
		}
		User user = userService.getUserById(userId);
		if (user == null) {
			json.getErrors().put("username", "手机号错误");
			json.setResult(false);
			return json;
		}
		if (!mailyzm.equals(user.getMailyanzhengma())) {
			json.getErrors().put("error", "账号对应的验证码错误");
			json.setResult(false);
			return json;

		}
		boolean flag = userService.updateUserById(AuthUtils.MD5(newpass), user.getUser_id().toString());
		if (flag) {

			json.setResult(true);

		}
		return json;
	}

	/** end 找回登录密码 added by liaoliyun ***/

	@ResponseBody
	@RequestMapping(value = "/login.json", method = RequestMethod.POST)
	public JsonVo<String> adminLogin(@RequestParam(value = "account") String name, @RequestParam(value = "password") String password, HttpServletRequest request, ModelMap modelMap) {
		JsonVo<String> json = new JsonVo<String>();

		try {
			/*
			 * String kaptcha = (String) request.getSession().getAttribute( com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
			 */
			// 1、查询数据库判断当前用户是否存在
			User user = userService.getUserById(name);
			if (null == user) {
				json.getErrors().put("username", "用户不存在");
			} else {
				// System.out.println(user.getUser_pass()+"--"+AuthUtils.MD5(password));
				if (StringUtils.isBlank(password) || !user.getUser_pass().equals(AuthUtils.MD5(password))) {
					json.getErrors().put("password", "密码错误请重试");
				} else {
					if (user.getIs_active() != 1) {
						json.getErrors().put("is_active", "用户未激活");
					}
					if (user.getIs_black() == 1 || user.getStatus() != 1) {
						json.getErrors().put("status", "用户禁止登录，请与网站管理员或客服人员联系");
					}
				}
			}

			json.check();

			// 2、登录后持久化用户状态
			// modelMap.addAttribute("user", user);
			request.getSession().setAttribute("user", user);
			request.getSession().setAttribute("account", name);
			Map<String, String> properties = PropertiesUtil.getInstance("/config.properties");
			String ip = properties.get("ip");
			request.getSession().setAttribute("ip", ip);

			// 3、日志记录
			String userIp = HttpRequestUtil.getIpAddress(request);
			LoginLog loginLog = new LoginLog();
			loginLog.setUser_ip(userIp);
			loginLog.setUser_id(user.getUser_id());
			loginLog.setCreate_time(new Date().getTime() / 1000);// 转化为秒
			userService.addLoginLog(loginLog);

		} catch (Exception e) {
			// 异常，重置验证码
			/*
			 * request.getSession().removeAttribute( com.google.code.kaptcha.Constants. ); json.setResult(false); json.getErrors().put("password", "用户名或密码错误"); json.setMsg("change_captcha");
			 */
		}
		return json;
	}

	@RequestMapping(value = "/reg.htm", method = RequestMethod.GET)
	public String reg(HttpServletRequest request, ModelMap modelMap) {
		return "/template/blog/register";
	}

	@RequestMapping(value = "/setPayPwd.htm", method = RequestMethod.GET)
	public String setPayPwd(HttpServletRequest request, ModelMap modelMap) {
		return "/business/setpaypwd";
	}

	@RequestMapping(value = "/payPwdAdmin.htm", method = RequestMethod.GET)
	public String payPwdAdmin(HttpServletRequest request, ModelMap modelMap) {
		return "/business/payPwdAdmin";
	}

	/**
	 * 发送验证码
	 * @param name
	 * @param password
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/verifyyzm.json", method = RequestMethod.POST)
	public Map<String, Object> sendVerify(@RequestParam(value = "account") String account, HttpServletRequest request, ModelMap modelMap, String status) {
		System.out.println("进入短信注册发送方法----verifyyzm.json");
		Map<String, Object> result = new HashMap<String, Object>();
		if(null!=request.getSession().getAttribute(SystemConstants.SMS_NAME)){
			if((boolean)request.getSession().getAttribute(SystemConstants.SMS_NAME)){
				System.out.println("发送验证码时间未到，不能发送验证码!");
				result.put("status", 10);
				result.put("info", "倒计时未结束，请稍后再试！");
				return result;
			}
		}
		// 重置验证码次数
		phoneYzmReset(request, account);
		User user = userService.getUserById(account);
		if (null != user) {
			if (null == user.getPhoneYzmCount()) {
				user.setPhoneYzmCount(0);
			}
			String code = "";
			// 生成验证码
			String capText = captchaProducer.createText();
			request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
			String message = "你的注册验证码为【" + capText + "】。请不要把验证码泄露给其他人。";
			String title = "运通注册验证码";
			boolean flag = false;
			if (RegexUtils.isMobileNO(account)) {
				if (user.getPhoneYzmCount() < 10) {
					if ("1".equals(status)) {
						code = sendsms.regSendSms(account, capText,request);
					} else if ("2".equals(status)) {
						code = sendsms.sendSmsByBackPwd(account, capText);
					} else if ("3".equals(status)) {
						code = sendsms.sendSmsByBackPayPwd(account, capText);
					}

					if ("2".equals(code)) {
						if (null != user) {
							phoneYzm(user.getUser_id().toString(), request, account);
							flag = true;
						} else {
							flag = true;
						}
					}
				} else {
					phoneYzm(user.getUser_id().toString(), request, account);
				}
				request.getSession().setAttribute(SystemConstants.SMS_NAME, true);
				// flag = sendsms.sendsms(account, capText);
			} else {
				flag = SimpleMailSender.sendSmtpMail(account, title, message);
			}

			if (flag) {
				result.put("status", 1);
				result.put("info", "发送成功，请注意查收");
			} else {
				result.put("status", 2);
				if ("2".equals(code)) {
					result.put("info", "发送失败，请稍后再试...");
				} else {
					result.put("info", "同一手机号码，一天只能发送10条验证码");
				}
			}
		} else {
			String code = "";
			// 生成验证码
			String capText = captchaProducer.createText();
			request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
			String message = "你的注册验证码为【" + capText + "】。请不要把验证码泄露给其他人。";
			String title = "运通注册验证码";
			boolean flag = false;
			if (RegexUtils.isMobileNO(account)) {
				code = sendsms.regSendSms(account, capText,request);
				request.getSession().setAttribute(SystemConstants.SMS_NAME, true);
				if ("2".equals(code)) {
					flag = true;
				}
				// flag = sendsms.sendsms(account, capText);
			} else {
				flag = SimpleMailSender.sendSmtpMail(account, title, message);
			}

			if (flag) {
				result.put("status", 1);
				result.put("info", "发送成功，请注意查收");
			} else {
				result.put("status", 2);
				if ("2".equals(code)) {
					result.put("info", "发送失败，请稍后再试...");
				} else {
					result.put("info", "同一手机号码，一天只能发送10条验证码");
				}
			}
		}
		return result;
	}

	/**
	 * 注册
	 * @param name
	 * @param password
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/reg.json", method = RequestMethod.POST)
	public Map<String, Object> reg(@RequestParam(value = "account") String account, @RequestParam(value = "password") String password, @RequestParam(value = "verify") String verify, HttpServletRequest request, ModelMap modelMap) {
		// request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, "1234");
		Map<String, Object> result = new HashMap<String, Object>();
		if (null == request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY)) {
			result.put("status", 5);
			result.put("info", "请先发送验证码到手机！");
			return result;
		}
		// 判断验证码是否正确
		if (!request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY).equals(verify)) {
			result.put("status", 3);
			result.put("info", "验证码错误！");
			return result;
		}
		User reguser = userService.getUserById(account);
		if (null != reguser) {
			result.put("status", 4);
			result.put("info", "用户名已存在,请重新填写");
			return result;
		}
		User user = new User();
		user.setReg_tel(account);
		user.setReg_type("tel");
		user.setNick_name(account);
		user.setUser_pass(AuthUtils.MD5(password));
		user.setIs_black(0);
		user.setIs_active(1);
		user.setStatus(1);
		user.setCreate_time(new Date());
		user.setSource(1);
		user.setIp(ClientIPUtils.getIpAddr(request));
		user.setCdn_status(0);
		user.setLm_zt(1);
		user.setPhoneYzmCount(1);
		user.setUser_name("");// 默认空名
		boolean flag = userService.addUser(user);
		if (flag) {
			User userNew = userService.getUserById(user.getReg_tel());
			request.getSession().setAttribute("user", userNew);
			request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, null);
			result.put("status", 1);
			result.put("info", "恭喜您，注册成功！");
		}
		return result;
	}

	/**
	 * 校验验证码
	 * @param name
	 * @param password
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/checkVerify.json", method = RequestMethod.POST)
	public Map<String, Object> checkVerify(@RequestParam(value = "verify") String verify, HttpServletRequest request, ModelMap modelMap) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (!"".equals(verify) && null != verify && verify.equals(request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY))) {
			result.put("status", 1);
			result.put("info", "验证成功");
		} else {
			result.put("status", 0);
			result.put("info", "验证错误");
		}

		return result;
	}

	public static void main(String[] args) {
		// MyCdnAction my=new MyCdnAction();
		// my.createParameterMap(null);
	}

	@ResponseBody
	@RequestMapping(value = "/zhmm.json", method = RequestMethod.POST)
	public Map<String, Object> zhmm(@RequestParam(value = "account") String account, @RequestParam(value = "verify") String verify, HttpServletRequest request, ModelMap modelMap) {
		Map<String, Object> result = new HashMap<String, Object>();
		String code = "";
		if (!verify.equals(request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY))) {
			result.put("status", 3);
			result.put("info", "验证码错误!");
		} else {
			User user = userService.getUserById(account);
			if (null == user) {
				result.put("status", 2);
				result.put("info", "用户不存在");
			} else {
				String rdPassword = rdPassword();
				boolean flag = userService.updateUserById(AuthUtils.MD5(rdPassword), account);
				if (flag) {
					// boolean flag2=false;
					String message = rdPassword;
					sendsms(account, message, result, "2", request);
					// code=sendsms.sendsms(account, message);
					/*
					 * if("2".equals(code)){ flag2=true; } if(flag2){ result.put("status", 1); result.put("info", "密码已发送到您的手机上，请查收"); }else{ result.put("status", 0); if("2".equals(code)){ result.put("info", "发送失败，请稍后再试..."); }else{ result.put("info", "同一手机号码，一天只能发送5条验证码"); } }
					 */
				}
			}
		}
		return result;
	}

	/**
	 * 
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/userInfoPage.htm", method = RequestMethod.GET)
	public String account(HttpServletRequest request, ModelMap modelMap) {
		User user = (User) request.getSession().getAttribute("user");
		String userId = user.getUser_id().toString();
		// 获取用户基本信息和银行卡信息、用户手动添加的属性信息
		User userinfo = userService.getUserBankById(userId);
		// System.out.println(userinfo.getReal_name()+"-------------------");
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		// 封装用户手动添加属性信息
		String multiProperty = userinfo.getMulti_property();
		if (!StringUtil.isEmptyOrBlank(multiProperty)) {
			JSONArray array = null;
			array = JSONArray.fromObject(multiProperty);
			Iterator<JSONObject> iter = array.iterator();
			while (iter.hasNext()) {
				JSONObject jsonObject = iter.next();
				Map<String, Object> jsmap = new HashMap<String, Object>();
				// jsmap.put("name", jsonObject.getString("name"));
				// jsmap.put("key", jsonObject.getString("key"));{"zdy_name":"撒","zdy_value":"阿
				// jsmap.put("value", jsonObject.getString("value"));
				jsmap.put("zdy_name", jsonObject.get("zdy_name"));
				jsmap.put("zdy_value", jsonObject.get("zdy_value"));
				list.add(jsmap);
			}
		}
		modelMap.addAttribute("userinfo", userinfo);
		modelMap.addAttribute("multiProperty", list);
		modelMap.addAttribute("zdy", multiProperty);
		modelMap.put("pageType", "完善资料");
		return "/business/editUserinfo";
	}

	// /**
	// * 描述： 进入用户信息完善（修改）页面
	// * 创建人：YangJ 邮箱:yangjie@sxw100.com
	// * 创建时间：2015年7月30日 下午12:04:11
	// * 修改备注：
	// * @version
	// *
	// */
	// @RequestMapping(value="/userInfoPage.htm")
	// public String userInfoPage(HttpServletRequest request,ModelMap modelMap){
	// //查询已填写信息
	// modelMap.put("pageType", "完善资料");
	// return "/business/editUserinfo";
	// }
	/**
	 * 完善用户资料
	 * @param name
	 * @param password
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/account.json", method = RequestMethod.POST)
	public Map<String, Object> wsaccount(@RequestParam(value = "company") String company, @RequestParam(value = "address") String address, @RequestParam(value = "personId") String personId, @RequestParam(value = "hukouAddr") String hukouAddr, @RequestParam(value = "fax") String fax, @RequestParam(value = "realname") String realname, @RequestParam(value = "dh") String dh, @RequestParam(value = "lxmall") String lxmall, @RequestParam(value = "bankname") String bankname, @RequestParam(value = "bankcard") String bankcard, @RequestParam(value = "bankusername") String bankusername, HttpServletRequest request, ModelMap modelMap) {

		// createParameterMap(request);
		// System.out.println(Arrays.asList(request.getParameterValues("zdy_name"))+"_______________-------------------------_______________--");
		// System.out.println( Arrays.asList(request.getParameterValues("zdy_value"))+"_______________-------------------------_______________--");

		// JSONArray zdy_name = JSONArray.fromObject(request.getParameterValues("zdy_name"));
		// JSONArray zdy_value = JSONArray.fromObject(request.getParameterValues("zdy_value"));

		JSONArray jsonArray = new JSONArray();
		String[] zdy_name = request.getParameterValues("zdy_name");
		String[] zdy_value = request.getParameterValues("zdy_value");
		if (zdy_name != null && zdy_value != null)
			for (int i = 0; i < zdy_name.length && i < zdy_value.length; i++) {
				JSONObject temp = new JSONObject();
				temp.put("zdy_name", zdy_name[i]);
				temp.put("zdy_value", zdy_value[i]);
				jsonArray.add(temp);
			}

		// json.put("zdy_name", );
		// json.put("zdy_value", request.getParameterValues("zdy_value"));
		// System.out.println(zdy_name.toString());
		User user = (User) request.getSession().getAttribute("user");

		user.setMulti_property(jsonArray.isEmpty() ? null : jsonArray.toString());
		user.setCompany(company);
		user.setAddress(address);
		user.setFax(fax);
		user.setReal_name(realname);
		user.setDh(dh);
		user.setLx_mall(lxmall);
		user.setBank_name(bankname);
		user.setBank_card(bankcard);
		user.setBank_username(bankusername);
		user.setPerson_id(personId);
		user.setHukou_addr(hukouAddr);
		// user.setZhifumima(zhifumima);
		boolean flag = userService.updateUserInfo(user);
		Map<String, Object> result = new HashMap<String, Object>();
		if (flag) {
			result.put("status", 1);
			result.put("info", "更新成功!");
		}
		return result;
	}

	/**
	 * 修改密码--静态跳转
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/password.htm", method = RequestMethod.GET)
	public String password(HttpServletRequest request, ModelMap modelMap) {
		User user = (User) request.getSession().getAttribute("user");
		String userId = user.getUser_id().toString();
		// 获取用户基本信息和银行卡信息
		// User userinfo = userService.getUserBankById(userId);
		// modelMap.addAttribute("userinfo", userinfo);
		modelMap.put("pageType", "修改密码");
		return "business/editPasswords";
	}

	/**
	 * 修改密码
	 * @param name
	 * @param password
	 * @param request
	 * @param modelMap
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/password.json", method = RequestMethod.POST)
	public Map<String, Object> password(@RequestParam(value = "oldpass") String oldpass, @RequestParam(value = "newpass") String newpass, @RequestParam(value = "newpass1") String newpass1, HttpServletRequest request, ModelMap modelMap) {
		Map<String, Object> result = new HashMap<String, Object>();
		refreshSessionUser(request);
		User user = (User) request.getSession().getAttribute("user");
		String userId = user.getUser_id().toString();
		String password = user.getUser_pass();
		if (!newpass.equals(newpass1)) {
			result.put("status", 2);
			result.put("info", "两次密码不一致!");
			return result;
		}
		if (!password.equals(AuthUtils.MD5(oldpass))) {
			result.put("status", 3);
			result.put("info", "原密码错误!");
			return result;
		}
		boolean flag = userService.updateUserById(AuthUtils.MD5(newpass1), userId);
		if (flag) {
			// request.getSession().setAttribute("user", null);
			refreshSessionUser(request);
			result.put("status", 1);
			result.put("info", "密码修改成功!");
		} else {
			result.put("status", 0);
			result.put("info", "密码修改失败!");
		}
		return result;
	}

	// 私有方法，内部调用
	private String rdPassword() {
		Random r = new Random();
		String ssource = "0123456789";
		char[] src = ssource.toCharArray();
		char[] buf = new char[6];
		int rnd;
		for (int i = 0; i < 6; i++) {
			rnd = Math.abs(r.nextInt()) % src.length;
			buf[i] = src[rnd];
		}
		return new String(buf);
	}

	/**   
	* 描述：   退出功能
	* 创建人：YangJ  邮箱:yangjie@sxw100.com   
	* 创建时间：2015年7月29日 上午10:12:00   
	* 修改备注：   
	* @version    
	*    
	*/
	@RequestMapping(value = "/exit.htm")
	public String exit(HttpServletRequest request) {
		Object user = request.getSession().getAttribute("user");
		if (user != null)
			request.getSession().removeAttribute("user");
		return "redirect:/web/toShowIndex.do";
	}

	/**   
	* 描述：   充值、转账时异步获取帐号信息
	* 创建人：YangJ  邮箱:yangjie@sxw100.com   
	* 创建时间：2015年8月3日 下午2:44:34   
	* 修改备注：   
	* @version    
	*    
	*/
	@RequestMapping("/checkUser.json")
	@ResponseBody
	public JsonVo checkUser(HttpServletRequest request) {
		// createParameterMap(request);
		JsonVo json = new JsonVo();
		paramsMap.clear();
		paramsMap.put("reg_tel", request.getParameter("reg_tel"));
		List<Map<String, Object>> tempList = userDao.queryUserByCondition(paramsMap);
		if (tempList != null && tempList.size() > 0) {
			json.setT(tempList.get(0));
			json.setResult(true);
		}
		return json;
	}

	/**个人中心--支付密码设置 **/
	@ResponseBody
	@RequestMapping(value = "/setPayPwd.json", method = RequestMethod.POST)
	public Map<String, Object> setPayPwd(@RequestParam(value = "verify") String verify, @RequestParam(value = "newpassword") String newpassword, @RequestParam(value = "repassword") String repassword, HttpServletRequest request, ModelMap modelMap) {
		Map<String, Object> json = new HashMap<String, Object>();
		refreshSessionUser(request);
		User user = (User) request.getSession().getAttribute("user");
		// request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY,"1234");
		if (!verify.equals(request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY))) {
			json.put("status", 3);
			json.put("info", "验证码错误");
			return json;
		}
		if (null == user) {
			json.put("status", 0);
			json.put("info", "用户不存在");
		} else {
			if (!newpassword.equals(repassword)) {
				json.put("status", 1);
				json.put("info", "新密码与确认密码不一致");
				return json;
			}
			boolean flag = userService.setPayPwd(newpassword, user.getUser_id().toString());
			if (flag) {
				json.put("status", 2);
				json.put("info", "设置支付密码成功");
				user = userDao.getUserById(user.getReg_tel());
				modelMap.put("userObj", user);// 用户信息 余额等
				// 刷新用户
				refreshSessionUser(request);

			}
		}
		return json;
	}

	/***个人中心--邮箱找回密码 ***/
	@ResponseBody
	@RequestMapping(value = "/returnPassByMail.json", method = RequestMethod.POST)
	public Map<String, Object> returnPassByMail(@RequestParam(value = "mailaddr") String mailaddr, HttpServletRequest request, ModelMap modelMap) {
		Map<String, Object> json = new HashMap<String, Object>();
		boolean flag = false;
		refreshSessionUser(request);
		User user = (User) request.getSession().getAttribute("user");
		if (null == user.getLx_mall() || ("").equals(user.getLx_mall())) {
			json.put("info", "没有注册邮箱，请用手机号找回密码");
			json.put("status", 0);
			return json;
		}
		if (!(mailaddr).equals(user.getLx_mall())) {
			json.put("info", "请输入注册邮箱地址");
			json.put("status", 1);
			return json;
		}
		String secretKey = UUID.randomUUID().toString(); // 密钥
		String href = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/user/resetmima.htm?sid=" + secretKey + "&account=" + user.getReg_tel();
		String title = "找回密码验证邮件，请勿回复";
		String content = "请点击【<font color=red>重置密码</font>】重置登录密码：\n\r <br><a href='" + href + "'>重置密码</a>";
		// String title="找回密码验证邮件，请勿回复";
		// String content="请点击以下链接重置登录密码：\n\r"+request.getScheme()+"://"+request.getServerName()+":"
		// +request.getServerPort()+request.getContextPath()+"/user/resetmima.htm?sid="+secretKey
		// +"&account="+user.getReg_tel();
		try {
			flag = SimpleMailSender.sendSmtpMail(mailaddr, title, content);
		} catch (Exception e) {
			// TODO: handle exception
			json.put("info", "邮件发送超时，请稍后再试");
			json.put("status", 3);
			return json;
		}
		if (flag) {
			flag = userService.updateMailYzmById(secretKey, user.getUser_id().toString());
		}

		if (flag) {
			json.put("info", "找回密码成功,请进入邮箱查看");
			json.put("status", 2);
		}
		return json;
	}

	/**个人中心-手机找回密码 **/
	@ResponseBody
	@RequestMapping(value = "/updatePassByPhone.json", method = RequestMethod.POST)
	public Map<String, Object> updatePassByPhone(@RequestParam(value = "account") String account, @RequestParam(value = "verify") String verify, @RequestParam(value = "newpassword") String newpassword, @RequestParam(value = "repassword") String repassword, HttpServletRequest request, ModelMap modelMap) {
		Map<String, Object> result = new HashMap<String, Object>();
		// request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY,"1234");
		if (!verify.equals(request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY))) {
			result.put("status", 3);
			result.put("info", "验证码错误!");
		} else {
			User user = (User) request.getSession().getAttribute("user");
			if (null == user) {
				result.put("status", 2);
				result.put("info", "请输入注册的手机号");
			} else {
				if (!account.equals(user.getReg_tel())) {
					result.put("status", 5);
					result.put("info", "请输入注册的手机号");
					return result;
				}
				if (!newpassword.equals(repassword)) {
					result.put("status", 4);
					result.put("info", "新密码和确认密码不一致");
					return result;
				}
				boolean flag = userService.updateUserById(AuthUtils.MD5(newpassword), user.getUser_id().toString());
				if (flag) {
					String message = newpassword;
					sendsms(account, message, result, "2", request);
					// boolean flag2 = sendsms.sendsms(account, message);
					// if(flag2){
					// result.put("status", 1);
					// / result.put("info", "密码已发送到您的手机上，请查收");
					// }else{
					// result.put("status", 0);
					// result.put("info", "发送失败，请稍后再试...");
					// }
				}
			}
		}
		return result;
	}

	/** 个人中心-支付密码修改 **/
	@ResponseBody
	@RequestMapping(value = "/updatePayPwd.json", method = RequestMethod.POST)
	public Map<String, Object> updatePayPwd(@RequestParam(value = "account") String account, @RequestParam(value = "verify") String verify, @RequestParam(value = "upnewpwd") String upnewpwd, @RequestParam(value = "uprenewpwd") String uprenewpwd, @RequestParam(value = "userpass") String userpass, @RequestParam(value = "upoldpwd") String upoldpwd, HttpServletRequest request, ModelMap modelMap) {
		Map<String, Object> json = new HashMap<String, Object>();
		User user = (User) request.getSession().getAttribute("user");
		// request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY,"1234");
		if (null != user) {
			if (!verify.equals(request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY))) {
				json.put("status", 0);
				json.put("info", "验证码错误!");
				return json;
			}
			if (!user.getUser_pass().equals(AuthUtils.MD5(userpass))) {
				json.put("status", 1);
				json.put("info", "登录密码错误!");
				return json;
			}
			if (!user.getZhifumima().equals(upoldpwd)) {
				json.put("status", 2);
				json.put("info", "支付原密码错误!");
				return json;
			}
			if (!upnewpwd.equals(uprenewpwd)) {
				json.put("status", 3);
				json.put("info", "支付密码与确认密码不一致!");
				return json;
			}
			if (!account.equals(user.getReg_tel())) {
				json.put("status", 5);
				json.put("info", "请输入注册的手机号!");
				return json;
			}
			boolean flag = false;
			flag = userService.setPayPwd(upnewpwd, user.getUser_id().toString());
			if (flag) {
				json.put("status", 4);
				json.put("info", "支付密码修改成功!");
				// 刷新用户
				refreshSessionUser(request);
			}
		} else {
			json.put("status", 5);
			json.put("info", "用户名不存在!");
			return json;
		}
		return json;
	}

	/**个人中心-手机找回支付密码 **/
	@ResponseBody
	@RequestMapping(value = "/returnPayPwdByPhone.json", method = RequestMethod.POST)
	public Map<String, Object> returnPayPwdByPhone(@RequestParam(value = "account") String account, @RequestParam(value = "verify") String verify, @RequestParam(value = "phnewpwd") String newpassword, @RequestParam(value = "phrenewpwd") String repassword, HttpServletRequest request, ModelMap modelMap) {
		Map<String, Object> result = new HashMap<String, Object>();
		// request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY,"1234");
		if (!verify.equals(request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY))) {
			result.put("status", 3);
			result.put("info", "验证码错误!");
		} else {
			User user = (User) request.getSession().getAttribute("user");
			// User user = userService.getUserById(account);
			if (null == user) {
				result.put("status", 2);
				result.put("info", "用户不存在");
				return result;
			} else {
				if (!account.equals(user.getReg_tel())) {
					result.put("status", 5);
					result.put("info", "请输入注册的手机号");
					return result;
				}
				if (!newpassword.equals(repassword)) {
					result.put("status", 4);
					result.put("info", "新支付密码和确认密码不一致");
					return result;
				}
				boolean flag = userService.setPayPwd(newpassword, user.getUser_id().toString());
				if (flag) {
					String message = newpassword;
					sendsms(account, message, result, "3", request);
					// 刷新用户
					refreshSessionUser(request);
					/*
					 * boolean flag2 = sendsms.sendsms(account, message); if(flag2){ result.put("status", 1); result.put("info", "密码已发送到您的手机上，请查收"); }else{ result.put("status", 0); result.put("info", "发送失败，请稍后再试..."); }
					 */
				}
			}
		}
		return result;
	}

	/***个人中心--邮箱找回支付密码 ***/
	@ResponseBody
	@RequestMapping(value = "/returnPayPwdByMail.json", method = RequestMethod.POST)
	public Map<String, Object> returnPayPwdByMail(@RequestParam(value = "mailaddr") String mailaddr, HttpServletRequest request, ModelMap modelMap) {
		Map<String, Object> json = new HashMap<String, Object>();
		boolean flag = false;
		refreshSessionUser(request);
		User user = (User) request.getSession().getAttribute("user");
		if (null == user.getLx_mall() || ("").equals(user.getLx_mall())) {
			json.put("info", "没有注册邮箱，请用手机号找回支付密码");
			json.put("status", 0);
			return json;
		}
		if (!(mailaddr).equals(user.getLx_mall())) {
			json.put("info", "请输入注册邮箱地址");
			json.put("status", 1);
			return json;
		}
		String secretKey = UUID.randomUUID().toString(); // 密钥
		String href = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/user/resetPayPwd.htm?sid=" + secretKey + "&account=" + user.getReg_tel();
		String title = "找回密码验证邮件，请勿回复";
		String content = "请点击【<font color=red>重置支付密码</font>】重置支付密码：\n\r <br><a href='" + href + "'>重置密码</a>";
		// String title="找回支付密码验证邮件，请勿回复";
		// String content="请点击以下链接重置登录密码：\n\r"+request.getScheme()+"://"+request.getServerName()+":"
		// +request.getServerPort()+request.getContextPath()+"/user/resetPayPwd.htm?sid="+secretKey
		// +"&account="+user.getReg_tel();
		flag = SimpleMailSender.sendSmtpMail(mailaddr, title, content);
		if (flag) {
			flag = userService.updateMailYzmById(secretKey, user.getUser_id().toString());
		}

		if (flag) {
			json.put("info", "找回支付密码成功,请进入邮箱查看");
			json.put("status", 2);
		}
		return json;
	}

	/** 邮件找回支付密码跳转 ***/
	@RequestMapping(value = "/resetPayPwd.htm", method = RequestMethod.GET)
	public String resetPayPwd(HttpServletRequest request, ModelMap modelMap, @RequestParam(value = "sid") String mailyzm, @RequestParam(value = "account") String account) {
		User user = userService.getUserById(account);
		if (user == null) {

			return null;
		}
		if (!mailyzm.equals(user.getMailyanzhengma())) {

			return null;

		}

		return "/template/blog/findpaypwd";
	}

	/** 邮箱找回支付密码 **/
	@ResponseBody
	@RequestMapping(value = "/resetPayPwdWithMail.json", method = RequestMethod.POST)
	public JsonVo<String> resetPayPwdWithMail(@RequestParam(value = "useId") String userId, @RequestParam(value = "newmm") String newpass, @RequestParam(value = "qrnewmm") String qrnewpass, @RequestParam(value = "mail_yzm") String mailyzm, HttpServletRequest request, ModelMap modelMap) {
		JsonVo<String> json = new JsonVo<String>();
		if (!newpass.equals(qrnewpass)) {
			json.getErrors().put("pwderror", "两次密码不一致");
			json.setResult(false);
			return json;
		}
		User user = userService.getUserById(userId);
		if (user == null) {
			json.getErrors().put("username", "用户名不存在");
			json.setResult(false);
			return json;
		}
		if (!mailyzm.equals(user.getMailyanzhengma())) {
			json.getErrors().put("error", "账号对应的验证码错误");
			json.setResult(false);
			return json;

		}
		boolean flag = userService.setPayPwd(newpass, user.getUser_id().toString());
		if (flag) {

			json.setResult(true);

		}
		return json;
	}

	/**
	 * 
	 * 描述：短信验证提示
	 * 创建人： 魏泽超
	 * 创建时间: 2016-4-11 上午11:17:48
	 * @version
	 */
	private void sendsms(String name, String capText, Map<String, Object> result, String status, HttpServletRequest request) {
		// 重置验证码次数
		phoneYzmReset(request, name);
		User user = userService.getUserById(name);
		if (user != null) {
			if (null == user.getPhoneYzmCount()) {
				user.setPhoneYzmCount(0);
			}
		} else {
			user.setPhoneYzmCount(0);
		}
		boolean flag = false;
		String code = "";
		if (user.getPhoneYzmCount() < 10) {
			if ("2".equals(status)) {
				code = sendsms.sendSmstoNewPwd(name, capText);
			} else {
				code = sendsms.sendSmstoNewPayPwd(name, capText);
			}
			if ("2".equals(code)) {
				if (null != user) {
					flag = true;
					phoneYzm(user.getUser_id().toString(), request, name);
				} else {
					flag = true;
				}
			}
		} else {
			phoneYzm(user.getUser_id().toString(), request, name);
		}

		if (flag) {
			result.put("status", 1);
			result.put("info", "密码已发送到您的手机上，请查收");
		} else {
			result.put("status", 0);
			if ("2".equals(code)) {
				result.put("info", "发送失败，请稍后再试...");
			} else {
				result.put("info", "同一手机号码，一天只能发送10条验证码");
			}
		}
	}

	// 重置验证码时间 和验证码次数
	private void phoneYzmReset(HttpServletRequest request, String account) {
		// User user = (User)request.getSession().getAttribute("user");
		User user = userService.getUserById(account);
		if (null != user) {
			if (null == user.getPhoneYzmCount()) {
				user.setPhoneYzmCount(0);
			}
			if (null != user.getPhoneYzmDate()) {
				Date nowDate = DateUtils.getCurrentDateByFormat("yyyy-MM-dd");
				if (nowDate.getTime() > user.getPhoneYzmDate().getTime()) {
					userService.setPhoneYzmDate(user.getUser_id().toString(), null);
					userService.setPhoneYzmCount(user.getUser_id().toString(), "2");
				}
			}
		}
	}

	// 设置验证码次数
	private int phoneYzm(String userId, HttpServletRequest request, String account) {
		int i = 1;
		User user = userService.getUserById(account);
		if (null != user) {
			if (null == user.getPhoneYzmCount()) {
				user.setPhoneYzmCount(0);
			}
			if (user.getPhoneYzmCount() < 10) {
				// 设置 验证码次数
				userService.setPhoneYzmCount(userId, "1");
			}

			if (user.getPhoneYzmCount() == 10) {
				// 设置禁止时间
				userService.setPhoneYzmDate(userId, DateUtils.getCurrentDateByFormat("yyyy-MM-dd"));
				i = 2;
			}
			if (null != request.getSession().getAttribute("user")) {
				refreshSessionUser(request);
			}
		}
		return i;
	}

	@ResponseBody
	@RequestMapping("/clearSession.do")
	public void clearSession(HttpServletRequest request) {
		request.getSession().setAttribute(SystemConstants.SMS_NAME, false);
		System.out.println("验证码发送session重置");
	}

}
